package ai.modules;

import util.ArrayList;
import util.Iterator;
import ai.AIUtil;
import engine.GameEngine;
import engine.data.Tile;
import engine.data.Unit;
import engine.data.UnitType;

public class PerceptionModule {

	public static final void init() {
		AIUtil.getCurrentAIPlayer().explorationPourcentage = getExplorationPourcentage();
		setEnnemiUnits();
	}

	public static final byte getExplorationPourcentage() {
		short tilesSeen = 0;
		for (short x = 0; x < GameEngine.map.width; x++) {
			for (short y = 0; y < GameEngine.map.height; y++) {
				if (GameEngine.map.getTile(x, y).isVisible[GameEngine.currPlayer.getId()])
					tilesSeen++;
			}
		}
		return (byte) (tilesSeen * 100 / (GameEngine.map.width * GameEngine.map.height));
	}

	public static final void setEnnemiUnits() {
		Iterator it = GameEngine.currPlayer.units.iterator();
		Unit currentUnit;
		ArrayList visitedTiles = new ArrayList();
		while (it.hasNext()) {
			currentUnit = (Unit) it.next();
			setEnnemiUnitsSeenByUnit(currentUnit, visitedTiles);
		}
	}

	public static final void setEnnemiUnitsSeenByUnit(Unit unit, ArrayList visitedTiles) {
		byte range = UnitType.getRP(unit.type);
		for (short i = (short) (unit.x - range); i <= unit.x + range; i++) {
			for (short j = (short) (unit.y - range); j <= unit.y + range; j++) {
				if (i >= 0 && j >= 0 && i < GameEngine.map.width && j < GameEngine.map.height) {
					Tile rangedTile = GameEngine.map.getTile(i, j);
					if (!visitedTiles.contains(rangedTile)){
					setEnnemiUnitsOnTile(rangedTile);
					visitedTiles.add(rangedTile);
				}
				}
			}
		}
	}

	public static final void setEnnemiUnitsOnTile(Tile tile) {
		if (tile.hasEnnemyUnits(GameEngine.currPlayer)) {
			Iterator it = tile.units.iterator();
			Unit currentUnit;
			while (it.hasNext()) {
				currentUnit = (Unit) it.next();
				if (!AIUtil.getCurrentAIPlayer().enemyUnits.contains(currentUnit))
					AIUtil.getCurrentAIPlayer().enemyUnits.add(currentUnit);
			}
		}

	}

	public static final String getString() {
		// TODO Auto-generated method stub
		StringBuffer res = new StringBuffer("AI Perception Module - turn ").append(GameEngine.turn).append(" - civ ").append(GameEngine.currPlayer.civilization).append(" : \n");
		res.append("explorationPourcentage: ").append(AIUtil.getCurrentAIPlayer().explorationPourcentage).append("%\n");
		res.append("enemyUnitsSeen: ").append(AIUtil.getCurrentAIPlayer().enemyUnits.size()).append("\n");
		return res.toString();
	}
}
